package thread;

//多线程不安全问题
class Test{
    public int count = 0;

    /**
     * load
     *  dd
     * save
     *
     * synchornized 给线程加锁 保证线程安全问题
     * 在线程调用add方法时,对对象进行加锁,方法结束时,进行解锁
     * 效率会变低,但依旧比单线程要快
     */
    synchronized public void add(){
        count++;
    }

    //public void add(){
    //        count++;
    //}
}
public class ThreadDemo13 {
    public static void main(String[] args) {
        Test test = new Test();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                test.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                test.add();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("count = " + test.count);
    }
}
